<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/10/22
 * Time: 16:01
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\common\business;

use app\common\lib\Show;
use app\common\validate\Admin as ValObj;
use app\common\model\mysql\Admin as ModelObj;
use think\Exception;
use think\facade\Session;

class Admin extends Base
{
    protected $valObj = null;
    protected $modelObj = null;

    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }

    /**
     * @param array $data
     * @return bool
     * @throws Exception
     */
    public function checkLogin(array $data = []): bool
    {
        if (!$this->valObj->scene('login')->check($data)) {
            throw new Exception($this->valObj->getError());
        }
        //根据用户名查询用户是否存在
        try {
            $admin = $this->modelObj->getAdminByUserInfo($data['move_user']);
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
        if (!$admin) {
            throw new Exception("用户不存在");
        }
        $res = $admin->toArray();
        $pwd = md5($data['move_pwd'] . $res['code']);
        if ($pwd != $res['move_pwd']) {
            throw new Exception("用户名和密码输入错误");
        }
        //修改数据登录时间
        $update_data = [
            "last_login_time" => time(),
            "last_login_ip" => request()->ip()
        ];
        try {
            $result = $this->modelObj->updateByData($res['id'], $update_data);
        } catch (\Exception $e) {
            throw new Exception("更新失败");
        }
        if ($result) {
            Session::set(config('admin.admin_session_key'), md5((string)time())."-" .$admin['id']. "-" . base64_encode(Show::json_encode($res)));
            return true;
        } else {
            return false;
        }
    }

    public function saveBtn(array $data = [])
    {
        $this->isValidateAdd($data,'pwd');
        $userId = explode("-",$data['admin']);
        try {
            $admin = $this->modelObj->getBaseById((int)$userId[1]);
        }catch (\Exception $e){
            throw new Exception("查询错误");
        }
        if($admin['move_pwd'] != md5($data['old_password'].$admin['code'])){
            throw new Exception("旧密码输入错误");
        }

        $update_data = [
            "move_pwd"=>md5($data['new_password'].$admin['code']),
            "update_time"=>time()
        ];
        try {
            $res = $this->modelObj->updateByData($admin['id'], $update_data);
        }catch (\Exception $e){
            throw new Exception("修改出错");
        }
        return $res;
    }

}